/**
 * 
 */
package com.game.jumpdino.logic.visual;

import com.game.jumpdino.logic.Playground;
import com.game.jumpdino.logic.VisualTurnedListener;

import android.graphics.Point;

/**
 * @author HugoGu
 *
 */
public class Kite extends Holder {
	private Playground playground;
	private int flyingHeight = 1000;
	private int flyedHeight = 0;
	private Point hookPoint = new Point(50, -50);
	private Point hookPointTurn = new Point(50, -36); 
	private float speed = -100;
	VisualTurnedListener lisenter;
	
	@Override
	public void onHit(VisualBase visual, final Playground ground){
		// Only affect once.
		if (flyedHeight < flyingHeight && !ground.avatar.isHasTool() && ground.avatar.getFollows().isEmpty()){
			this.playground = ground;
			playSound(ground.getContext());
			this.setG(4.0f);
			this.setVy(speed);
			visual.setVx(0.0f);
			visual.setVy(-12);
			VisualTurnedListener lisenter = new VisualTurnedListener(){
				public void onTurned(VisualBase who) {
					if (ground.avatar.getTurned()){
						float targetX = who.getPosition().left + hookPointTurn.x;
						float targetY = who.getPosition().top + hookPointTurn.y;
						getPosition().offset(Math.round(targetX - getPosition().left), Math.round(targetY - getPosition().top));
					} else {
						float targetX = who.getPosition().left + hookPoint.x;
						float targetY = who.getPosition().top + hookPoint.y;
						getPosition().offset(Math.round(targetX - getPosition().left), Math.round(targetY - getPosition().top));
					}
				}
			};
			ground.avatar.addTurnedListener(lisenter);
			if (ground.avatar.getTurned()){
				float targetX = visual.getPosition().left + hookPointTurn.x;
				float targetY = visual.getPosition().top + hookPointTurn.y;
				this.move(targetX - this.getPosition().left, targetY - this.getPosition().top);
			} else {
				float targetX = visual.getPosition().left + hookPoint.x;
				float targetY = visual.getPosition().top + hookPoint.y;
				this.move(targetX - this.getPosition().left, targetY - this.getPosition().top);
			}
			ground.avatar.setHasTool(true);
			visual.follow(this);
		}
	}
	
	//Override
	public void onMove(float offsetX, float offsetY){
		if (flyedHeight > flyingHeight){
			while(getFollows().size() > 0){
				// The un-follow method will remove the follow;
				getFollows().get(0).unFollow(this);
			}
			playground.avatar.removeTurnedListener(lisenter);
			playground.avatar.setHasTool(false);
		} else if (getFollows().size() > 0 && offsetY < 0){
			flyedHeight += Math.max(Math.abs(offsetY), Math.abs(getVelocity().y));
		}
	}
}
